package upload

import (
	"context"
	v1 "devops-super/api/file/v1"
	"devops-super/internal/consts"
	"devops-super/internal/dao"
	"devops-super/internal/model/do"
	"devops-super/internal/service"
	"devops-super/utility/util/strUtil"
	"encoding/base64"
	"errors"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"
	"io/ioutil"
	"os"
	"strings"
	"time"
)

type Local struct {
}

func (s *Local) Upload(ctx context.Context, file *ghttp.UploadFile) (result v1.UploadResponse, err error) {
	if file == nil {
		err = errors.New("file is empty")
		return
	}
	r := g.RequestFromCtx(ctx)
	// Add check for nil request
	if r == nil {
		err = errors.New("failed to get request from context")
		return
	}
	urlPerfix := fmt.Sprintf("http://%s/", r.Host)
	p := strings.Trim(consts.UploadPath, "/")
	sp := service.Mysys().GetStaticPath(ctx)
	if sp != "" {
		sp = strings.Trim(sp, "/")
	}
	nowData := time.Now().Format("2006/01/02")
	// 包含静态文件夹的路径
	fullDirPath := sp + "/" + p + "/" + nowData
	fileName, err := file.Save(fullDirPath, true)
	if err != nil {
		glog.Line().Error(ctx, err.Error())
		return
	}
	// 不含静态文件夹的路径
	fullPath := p + "/" + nowData + "/" + fileName

	result = v1.UploadResponse{
		Size:     file.Size,
		Path:     fullPath,
		FullPath: urlPerfix + fullPath,
		Name:     file.Filename,
		Type:     file.Header.Get("Content-type"),
	}

	serverKey := service.Mysys().GetMyServerKey(ctx)

	// 数据库记录文件信息
	dao.AppFiles.Ctx(ctx).Insert(do.AppFiles{
		ServerKey: serverKey,
		Source:    consts.AppFileSource_Local,
		Bucket:    p + "/" + nowData + "/",
		Path:      fileName,
		Size:      file.Size,
		CreatedAt: gtime.Now(),
	})

	return
}

func (s *Local) UploadBase64(ctx context.Context, base64Str string) (result v1.UploadResponse, err error) {
	r := g.RequestFromCtx(ctx)
	urlPerfix := fmt.Sprintf("http://%s/", r.Host)
	p := strings.Trim(consts.UploadPath, "/")
	sp := service.Mysys().GetStaticPath(ctx)
	if sp != "" {
		sp = strings.Trim(sp, "/")
	}
	nowData := time.Now().Format("2006/01/02")

	// 将Base64字符串解码为字节数组

	newStr := strings.Replace(base64Str, "data:image/png;base64,", "", -1)

	data, err := base64.StdEncoding.DecodeString(newStr)
	if err != nil {
		return
	}

	// 包含静态文件夹的路径
	fullDirPath := sp + "/" + p + "/" + nowData
	fname := strUtil.RandomStr(10) + ".png"
	fullFileName := fullDirPath + "/" + fname
	err = ioutil.WriteFile(fullFileName, data, 0644)
	if err != nil {
		return
	}
	// 不含静态文件夹的路径
	fullPath := p + "/" + nowData + "/" + fname

	file, err := os.Open(fullFileName)
	if err != nil {
		return
	}
	defer file.Close()
	info, err := file.Stat()
	if err != nil {
		return
	}
	result = v1.UploadResponse{
		Size:     info.Size(),
		Path:     fullPath,
		FullPath: urlPerfix + fullPath,
		Name:     fname,
		Type:     "image/jpeg",
	}
	serverKey := service.Mysys().GetMyServerKey(ctx)
	// 数据库记录文件信息
	dao.AppFiles.Ctx(ctx).Insert(do.AppFiles{
		ServerKey: serverKey,
		Source:    consts.AppFileSource_Local,
		Bucket:    p + "/" + nowData + "/",
		Path:      fname,
		Size:      info.Size(),
		CreatedAt: gtime.Now(),
	})
	return
}
